package cn.zut.hhr.class1.config;

import cn.zut.hhr.class1.handler.MyAuthenticationFailHandler;
import cn.zut.hhr.class1.handler.MyAuthenticationSuccessHandler;
import cn.zut.hhr.class1.service.impl.SysSecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration(proxyBeanMethods = false)
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends
        WebSecurityConfigurerAdapter {
    @Autowired
    private SysSecurityService sysSecurityService;
    @Resource
    private MyAuthenticationSuccessHandler
            myAuthenticationSuccessHandler;
    @Resource
    private MyAuthenticationFailHandler
            myAuthenticationFailHandler;
    @Autowired
    private DataSource dataSource;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(sysSecurityService).passwordEncoder(password());

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .defaultSuccessUrl("/index").permitAll()//登录后的跳转路径
                .and().logout().logoutUrl("/logout").logoutSuccessUrl("/index.html")//退出后回主页
                .and().authorizeRequests()
                .antMatchers("/","/index").permitAll()//无需登录即可访问的路径
                .antMatchers("/adminIndex").hasAuthority("admin")//只有主人管理员能访问
                .antMatchers("/anyIndex").hasAnyAuthority("admin","user")//普通用户也可以访问
                .anyRequest().authenticated()
                .and().exceptionHandling().accessDeniedPage("/fail.html")//自定义403页面
                .and().csrf().disable();//关闭csrf检查
    }

    @Bean
    PasswordEncoder password(){
        return new BCryptPasswordEncoder();
    }

}
